package com.tianda.his.modules.system.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.crypto.digest.Digester;
import cn.hutool.crypto.digest.MD5;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tianda.his.commons.constant.Constants;
import com.tianda.his.commons.enums.ErrorCodeAndMessageEnum;
import com.tianda.his.commons.exception.BusinessException;
import com.tianda.his.commons.utils.LoginUtils;
import com.tianda.his.modules.system.dto.LoginDto;
import com.tianda.his.modules.system.dto.UserDto;
import com.tianda.his.modules.system.entity.*;
import com.tianda.his.modules.system.mapper.SysMenuMapper;
import com.tianda.his.modules.system.mapper.SysRoleMapper;
import com.tianda.his.modules.system.mapper.SysUserMapper;
import com.tianda.his.modules.system.service.ISysUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tianda.his.modules.system.vo.MenuTreeVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.management.relation.Role;
import java.awt.*;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 用户信息表 服务实现类
 * </p>
 *
 * @author jinken
 * @since 2025-09-12
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService {

    @Autowired
    private SysRoleMapper roleMapper;

    @Autowired
    private SysMenuMapper menuMapper;

    @Override
    public void login(LoginDto loginDto) {
        //根据用户名查询用户
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUser::getPhone,loginDto.getUsername());

        SysUser sysUser = this.getOne(queryWrapper);

        if(Objects.nonNull(sysUser)){
            //用户密码+slat  :  123456JHGDOIWE
            String pwd = loginDto.getPassword() + sysUser.getSalt();
            System.out.println("pwd = " + pwd);
            //md5加密密码
            String md5Password = DigestUtil.md5Hex(pwd);
            System.out.println("md5Password = " + md5Password);
            System.out.println(sysUser.getPassword());


            //比较密码
            if(md5Password.equals(sysUser.getPassword())){
                //登录成功:Sa-token登录
                StpUtil.login(sysUser.getPhone());
                //保存登录用户为全局信息
                LoginUtils.setLoginUser(sysUser);


            }else{
                //抛出逻辑异常
                throw new BusinessException(ErrorCodeAndMessageEnum.LOGIN_ERROR);
            }
        }else{
            //抛出逻辑异常
            throw new BusinessException(ErrorCodeAndMessageEnum.LOGIN_ERROR);
        }


    }

    @Override
    public ActiveUser getInfo() {

        //获取登录账号
        String phone = StpUtil.getLoginIdAsString();

        //根据用户名查询用户
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUser::getPhone,phone);
        SysUser sysUser = this.getOne(queryWrapper);

        ActiveUser activeUser = new ActiveUser();
        activeUser.setUsername(sysUser.getUserName());
        activeUser.setPicture(sysUser.getPicture());



        //查询用户的角色


        if(Constants.USER_ADMIN.equals(sysUser.getUserType())){
            activeUser.setRoles(Arrays.asList("超级管理员"));

            List<SysMenu>   menus = menuMapper.selectList(null);

            //转换权限名称
            List<String> menuNames = menus.stream().map(SysMenu::getMenuName).toList();
            activeUser.setPermissions(menuNames);

        }else{
            List<SysRole> roles = roleMapper.selectRolesByUsername(phone);
            //过滤所有的橘色名称
            List<String> list = roles.stream().map(SysRole::getRoleName).toList();
            activeUser.setRoles(list);


            List<SysMenu> menus = menuMapper.selectMenusByUsername(phone);
            //转换权限名称
            List<String> menuNames = menus.stream().map(SysMenu::getMenuName).toList();
            activeUser.setPermissions(menuNames);
        }


        return activeUser;
    }

    @Override
    public List<MenuTreeVo> getMenus() {
        //获取登录账号
        String phone = StpUtil.getLoginIdAsString();
        //根据用户名查询用户
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUser::getPhone,phone);

        SysUser sysUser = this.getOne(queryWrapper);
        List<SysMenu> menus = menuMapper.selectMenusByUsername(phone);
        if(Constants.USER_ADMIN.equals(sysUser.getUserType())){
            menus = menuMapper.selectList(null);
        }
        //转换成前端MenuTreeVo
        List<MenuTreeVo> menuTreeVos = menus.stream().map(menu -> {
            MenuTreeVo menuTreeVo = new MenuTreeVo();
            menuTreeVo.setName(menu.getMenuName());
            menuTreeVo.setSerPath(menu.getPath());
            return menuTreeVo;
        }).toList();


        return menuTreeVos;
    }

    @Override
    public Page<SysUser> listDeptForPage(UserDto userDto) {


        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        //TODO 构建条件

        Page<SysUser> sysDeptPage = new Page<>(userDto.getPageNum(), userDto.getPageSize());

        this.page(sysDeptPage, queryWrapper);

        return sysDeptPage;
    }
}
